<style type="text/css">
    .img-container,
    .img-preview {
        background-color: #f7f7f7;
        text-align: center;
        max-width: 100%;
    }

    .img-container {
        margin-bottom: 1rem;
        height: 600px;
        overflow-y: auto;
        overflow-x: hidden;
    }
    .txt-preview {
        margin-left: 10px;
        border: 1px solid;
        height: 500px;
        overflow-y: auto;
        overflow-x: hidden;
    }

    .txt-preview ul{
        margin: 10px;
    }

    .txt-preview li{
        cursor: pointer;
    }
    .txt-preview li a:hover {
        background-color: #9F9F9F;
    }

    .ocr-anchor-box {
        display: flex;
        width: 100%;
        /*margin: 15px 0;*/
    }
    .ocr-anchor-box-input {
        width: 90%;
        min-height: 26px;
    }

    .ocr-anchor-box-input input,textarea {
        width: 95%;
        padding: 5px;
    }
    .ocr-anchor-box-close {
        width: 24px;
        height: 24px;
        margin-left: 24px;
    }
</style>
<div class="layui-fluid" id="image-scan" style="padding: 10px;">
    <div class="layui-row layui-col-space8 febs-container">
        <div class="layui-col-md12 layui-col-sm12 layui-col-xs12">
            <div class="layui-card">
                <div class="layui-card-header">发票识别</div>
                <div class="layui-card-body">
                    <div class="layui-btn-container">
                        <!--文件上传-->
                        <button class="layui-btn layui-btn-normal" id="btn-upload">上传</button>
                        <input type="file" id="uploadfile" style="display: none;">
                    </div>
                    <div class="layui-row">
                        <div class="layui-col-md8">
                            <div class="img-container">
                                <img id="image" th:src="@{febs/images/syfp1.jpg}" alt="Picture" style="display: none;">
                                <canvas id="drawable" width="545" height="400" style="border:1px solid #000000;" ></canvas>
                                <!--<div id="opt_div" style="border:1px solid #000000; position: absolute; top: 0; left: 0;"></div>-->
                            </div>
                        </div>
                        <div class="layui-col-md4">
                            <div class="txt-preview">
                                <ul id="scan-preview">
                                </ul>
                            </div>
                            <!--
                            <div class="txt-preview">
                                <textarea id="result" style="width: 100%;" rows="10"></textarea>
                                <button class="layui-btn layui-btn-normal" id="btn-ok">提取</button>
                            </div>
                            -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script th:src="@{febs/data/syfp1.js}"></script>
<script data-th-inline="none">
    layui.use(['febs', 'form', 'layer', 'upload', 'zrender'], function () {
        var $ = layui.$,
            $view = $('#image-scan'),
            upload = layui.upload,
            zrender = layui.zrender,
            febs = layui.febs;
        var $image, $drawable;
        var scale, zr;
        var uploadImage = false;
        var options = {
            //aspectRatio: 16 / 9,
            viewMode: 1,
            guides: true,
            crop: function(e) {
                //console.log(e);
            }
        };
        onInit();

        function onInit() {
            $image = $view.find('#image');
            $drawable = $view.find('#drawable');
            $image[0].onload = function () {
                console.log('Image loaded !');

                if (!zr) {
                    var width = $drawable.parent().width();
                    scale = width / this.naturalWidth;
                    $drawable[0].width = width;
                    $drawable[0].height = this.naturalHeight * scale;
                    zr = zrender.init($drawable[0]);
                }
                zr.clear();
                var image = new zrender.Image({
                    style: {
                        image: $image[0],
                        width: $drawable[0].width,
                        height: $drawable[0].height
                    }
                });
                zr.add(image);
                if (uploadImage) {
                    uploadImage = false;
                    return
                }
                reloadContent(_imagedata);
            };

            $view.find("#scan-preview").on('click', function (e) {
                if (e.target.tagName.toLowerCase() == 'img') {
                    $(e.target).parents("li").remove();
                }
            });

            //拖拽上传
            upload.render({
                elem: '#btn-upload'
                , url: ctx + 'others/imageScan/fileup'
                , before: function (obj) {
                    layer.load('loading')
                    //预读本地文件示例，不支持ie8
                    obj.preview(function (index, file, result) {
                        uploadImage = true;
                        $image.attr('src', result); //图片链接（base64）
                    });
                    //$(".closePic").show();
                    //$pic.show();
                    //$("#uploadFiles").hide();
                    //图片放大
                    /*$pic.click(function () {
                        $(this).after("<div  class='enlargeImg_wrapper'></div>");
                        var imgSrc = $(this).attr('src');
                        $(".enlargeImg_wrapper").css("background-image", "url(" + imgSrc + ")");
                        $('.enlargeImg_wrapper').fadeIn(200);
                        //关闭并移除图层
                        $('.enlargeImg_wrapper').click(function () {
                            $(this).fadeOut(200).remove();
                        })
                    })*/
                }
                , done: function (res) {
                    layer.closeAll('loading')
                    if (res.code == 200) {
                        reloadContent(JSON.parse(res.data));
                        //$imagePath.val(res.data[0].filePath);
                        febs.alert.success('识别成功');
                    } else {
                        console.log(res.message);
                        febs.alert.warn('识别失败');
                    }
                },
                error: function () {
                    layer.closeAll('loading')
                    febs.alert.warn('识别失败');
                }
            });

/*
            $view.find('#btn-upload').on('click', function () {
                uploadImage = true;
                $view.find("#uploadfile").trigger('click');
            });
            $view.find("#uploadfile").on("change",function(){
                //var fr = new FileReader();
                var file = this.files[0];

                if(!/image\/\w+/.test(file.type)){
                    febs.alert.warn(file.name + "不是图片文件！");
                    return false;
                }else if(file.size>2*1024*1024){
                    febs.alert.warn('图片大小不能超过2M');
                    return false;
                }

                var uploadedImageURL = URL.createObjectURL(file);
                $image.attr('src', uploadedImageURL);
                imageCompress(uploadedImageURL, $drawable[0].width, 1, onImage);
                //$image.cropper('destroy').attr('src', uploadedImageURL).cropper(options);
            });
*/
            $view.find('#btn-ok').on('click', function() {
                var input = $view.find("#scanText").val();
                var ocrInfo = findTextInImageData(input);
                if (ocrInfo) {
                    console.log(ocrInfo);
                }

                /*
                var rectCanvas = $image.cropper('getCroppedCanvas', {
                    fillColor: '#fff',
                    imageSmoothingEnabled: false,
                    imageSmoothingQuality: 'high',
                });
                var rectImage = $view.find('#preview');
                rectImage[0].src = rectCanvas.toDataURL();
                submitData();
                */
            });

            //console.log(_imagedata);

/*
            var scanPreview = $view.find("#scan-preview");
            var prism_wordsInfo = _imagedata.prism_wordsInfo;
            $.each(prism_wordsInfo, function (index, value) {
                scanPreview.append("<li data-id='"+index+"'><a>"+value.word+"</a></li>")
            })
            scanPreview.find("li").on('click', onSelectText);

            var tablePreview = $view.find("#table-preview");
            var prism_tablesInfo = _imagedata.prism_tablesInfo;
            $.each(prism_tablesInfo, function (cindex, cellInfos) {
                $.each(cellInfos.cellInfos, function (index, value) {
                    tablePreview.append("<li data-id='"+index+"'><a>"+value.word+"</a></li>")
                })
            })
            tablePreview.find("li").on('click', onSelectTableText);
*/
        }

        function reloadContent(imagedata) {
            if (imagedata.prism_tablesInfo && imagedata.prism_tablesInfo.length > 0) {
                initAllContent(imagedata.prism_tablesInfo[0]['cellInfos']);
            }
            if (imagedata.prism_wordsInfo) {
                initAllContent(imagedata.prism_wordsInfo);
            }

        }

        function initAllContent(wordsInfo) {
            $.each(wordsInfo, function (index, value) {
                if (index > 1) {
                    //return;
                }
                var lines = new zrender.Polygon({
                    shape: {
                        points: [
                            [value.pos[0].x * scale, value.pos[0].y * scale],
                            [value.pos[1].x * scale, value.pos[1].y * scale],
                            [value.pos[2].x * scale, value.pos[2].y * scale],
                            [value.pos[3].x * scale, value.pos[3].y * scale],
                            [value.pos[0].x * scale, value.pos[0].y * scale],
                        ],
                    },
                    style: {
                        fill: 'transparent',
                        stroke: 'transparent'
                    },
                    cursor: 'pointer',
                }).on('click', function (e) {
                    showSelectText(e.target['el_data'].word);
                    //console.log(e.target['el_data'].word);
                }).on('mouseover', function (e) {
                    e.target.attr({
                        style: {
                            stroke: 'red',
                        }
                    });
                }).on('mouseout', function (e) {
                    e.target.attr({
                        style: {
                            stroke: 'transparent',
                        }
                    });
                });
                lines['el_data'] = value;

                zr.add(lines)
            });

            function showSelectText(text) {
                var scanPreview = $view.find("#scan-preview");
                scanPreview.append('<li>'+
                    '<div class="ocr-anchor-box">'+
                    '<div class="ocr-anchor-box-input">'+
                    '<span class="next-input next-medium full-width">'+
                    '<textarea>'+text+'</textarea>'+//'<input height="100%" autocomplete="off" value="'+text+'">'+
                    '</span>' +
                    '</div>'+
                    '<div class="ocr-anchor-box-close">'+
                    '<img class="ocr-close-img" src="febs/images/close.jpg">'+
                    '</div>'+
                    '</div>'+
                    '</li>');
            }

            /*
            var optDiv = $view.find("#opt_div");
            var prism_wordsInfo = _imagedata.prism_wordsInfo;
            $.each(prism_wordsInfo, function (index, value) {
                if (index > 1) {
                    return;
                }
                console.log(value.pos);
                var top = value.pos[0].y * scale;
                var left = value.pos[0].x * scale;
                var width = (value.pos[1].x - value.pos[0].x) * scale;
                var height = (value.pos[3].y - value.pos[0].y) * scale;
                console.log("("+top+","+left+","+width+","+height+")");
                optDiv.append("<div style='position: absolute; border: blue 1px solid; transform:rotate(-3deg); top:"+top+"px; left:"+left+"px; width: "+width+"px; height: "+height+"px;'></div>")
            })
            */
        }
        function onSelectTableText() {
            var index = $(this).data('id');
            var wordsInfo = _imagedata.prism_tablesInfo[0]['cellInfos'][index];
            var ctx = $drawable[0].getContext('2d');
            ctx.lineWidth = 1;
            ctx.strokeStyle="blue";
            ctx.beginPath();
            ctx.moveTo(wordsInfo.pos[0].x * scale, wordsInfo.pos[0].y * scale);
            ctx.lineTo(wordsInfo.pos[3].x * scale, wordsInfo.pos[3].y * scale);
            ctx.lineTo(wordsInfo.pos[2].x * scale, wordsInfo.pos[2].y * scale);
            ctx.lineTo(wordsInfo.pos[1].x * scale, wordsInfo.pos[1].y * scale);
            ctx.lineTo(wordsInfo.pos[0].x * scale, wordsInfo.pos[0].y * scale);
            ctx.stroke();
            console.log(wordsInfo);
        }

        function onSelectText() {
            var index = $(this).data('id');
            var wordsInfo = _imagedata.prism_wordsInfo[index];
            var ctx = $drawable[0].getContext('2d');
            ctx.lineWidth = 1;
            ctx.strokeStyle="blue";
            ctx.beginPath();
            ctx.moveTo(wordsInfo.pos[0].x * scale, wordsInfo.pos[0].y * scale);
            ctx.lineTo(wordsInfo.pos[3].x * scale, wordsInfo.pos[3].y * scale);
            ctx.lineTo(wordsInfo.pos[2].x * scale, wordsInfo.pos[2].y * scale);
            ctx.lineTo(wordsInfo.pos[1].x * scale, wordsInfo.pos[1].y * scale);
            ctx.lineTo(wordsInfo.pos[0].x * scale, wordsInfo.pos[0].y * scale);
            ctx.stroke();
            //console.log(wordsInfo);
        }

        function findTextInImageData(text) {
            var prism_wordsInfo = _imagedata.prism_wordsInfo;
            $.each(prism_wordsInfo, function (index, value) {
                if (value.word == text) {
                    return value;
                }
            })
            return null;
        }

        /**
         * [imageCompress 图片压缩]
         * @param  {[Array]} imgSrc       [传入图片地址]
         * @param  {Number} [width=1024]  [图片需要压缩的宽度,单位：px]
         * @param  {Number} [quality=1]   [图片需要压缩的质量，0~1之间]
         * @return {[type]}               [返回base64 jpeg格式图片]
         */
        function imageCompress (imgSrc, width, quality, callback) {
            if (width == undefined) {
                width = 1024;
            }
            if (quality == undefined) {
                quality = 1;
            }
            var img = null;
            var canvas = document.createElement('canvas');
            var ctx = canvas.getContext('2d');
            var oImg = new window.Image();
            oImg.src = imgSrc;
            oImg.onload = function () {
                var height = width / (this.naturalWidth / this.naturalHeight)
                // 如果压缩的宽度大于图片自身的宽度，采取图片自身的宽度
                if (this.naturalWidth <= width) {
                    width = this.naturalWidth
                    height = this.naturalHeight
                }
                canvas.width = width
                canvas.height = height
                ctx.drawImage(this, 0, 0, width, height)
                img = canvas.toDataURL('image/jpeg', quality);
                callback(img);
            }
        }


        function submitData() {

        }
/*
        form.on('submit(news-add-form-submit)', function (data) {
            if($imagePath.val() == ""){
                febs.alert.warn("请上传标题缩略图");
                return false;
            }
            var url = ctx + 'ftaNews';
            febs.post(url, {
                // 标题
                title: $view.find("input[name='title']").val().toString().trim(),
                // 类别
                ntype: $view.find("select[name='ntype']").val(),
                // 类别
                ntype2: $view.find("select[name='ntype2']").val(),
                // 类别
                ntype3: $view.find("select[name='ntype3']").val(),
                // 类别
                ntype4: $view.find("select[name='ntype4']").val(),
                // 发布时间
                publishTime: $view.find("input[name='publishTime']").val(),
                // 内容
                content: UE.getEditor('ftanewseditor').getContent(),
                keyword: $view.find("input[name='keyword']").val(),
                description: UE.getEditor('ftanewseditor').getContentTxt().substring(0,200),
                topFlg: $view.find("input[name='topFlg']:checked").val(),
                statementFlg: $view.find("input[name='statementFlg']:checked").val(),
                // 文件名称
                imagePath: $imagePath.val()
            }, function () {
                layer.closeAll();
                febs.alert.success('保存成功');
                $('#febs-news-item').find('#query').click();
            });
            return false;
        });

        //拖拽上传
        upload.render({
            elem: '#uploadFiles'
            , url: ctx + 'others/imageScan/fileup'
            , before: function (obj) {
                layer.load('loading')
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    $pic.attr('src', result); //图片链接（base64）
                });
                $(".closePic").show();
                $pic.show();
                $("#uploadFiles").hide();
                //图片放大
                $pic.click(function () {
                    $(this).after("<div  class='enlargeImg_wrapper'></div>");
                    var imgSrc = $(this).attr('src');
                    $(".enlargeImg_wrapper").css("background-image", "url(" + imgSrc + ")");
                    $('.enlargeImg_wrapper').fadeIn(200);
                    //关闭并移除图层
                    $('.enlargeImg_wrapper').click(function () {
                        $(this).fadeOut(200).remove();
                    })
                })
            }
            , done: function (res) {
                layer.closeAll('loading')
                if (res.code == 200) {
                    $imagePath.val(res.data[0].filePath);
                }
            },
            error: function () {
                layer.closeAll('loading')
            }
        });
        // 图片删除
        $(".closePic").click(function () {
            $(".closePic").hide();
            $pic.hide();
            $("#uploadFiles").show();
            //$('#pic').attr('src', './img/jiajia.png');
            //$(".imgBox").append("<img class=\"layui-upload-img\" id=\"pic\">");
        })
*/
    });
</script>